﻿using System;
using System.IO;

using Nop.Core;
using Nop.Core.Domain.Media;
using Nop.Core.Infrastructure;
using Nop.Services.Configuration;

namespace RonsHouse.Plugin.Misc.AlternativeStorage.Services
{
	public partial class FileSystemStorageProvider : IAlternativeStorageProvider
	{
		private readonly ISettingService _settingService;
		private readonly IWebHelper _webHelper;

		private readonly string FILE_NAME_FORMAT = "{0}_{1}{2}";

		public FileSystemStorageProvider()
		{
			this._settingService = EngineContext.Current.Resolve<ISettingService>();
			this._webHelper = EngineContext.Current.Resolve<IWebHelper>();
		}

		public FileSystemStorageProvider(ISettingService settingService, IWebHelper webHelper)
		{
			this._settingService = settingService;
			this._webHelper = webHelper;
		}

		public byte[] Get(Download download)
		{
			byte[] bytes = null;

			var settings = _settingService.LoadSetting<AlternativeStorageSettings>();
			if (HasValidSettings(settings))
			{
				var filePath = _webHelper.MapPath(Path.Combine(settings.FileSystemPicturePath, String.Format(FILE_NAME_FORMAT, download.Id.ToString(), download.Filename, download.Extension)));
				if (File.Exists(filePath))
				{
					using (MemoryStream stream = new MemoryStream())
					{
						using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
						{
							bytes = new byte[file.Length];
							file.Read(bytes, 0, (int)file.Length);
							file.Close();
						}
						stream.Close();
					}
				}
				else
				{
					throw new FileNotFoundException("Unable to find the specified file", filePath);
				}
			}

			return bytes;
		}

		public void Save(Download download, byte[] data)
		{
			var settings = _settingService.LoadSetting<AlternativeStorageSettings>();
			if (HasValidSettings(settings))
			{
				var folderPath = _webHelper.MapPath(settings.FileSystemPicturePath);
				if (!Directory.Exists(folderPath))
				{
					Directory.CreateDirectory(folderPath);
				}

				var filePath = _webHelper.MapPath(Path.Combine(settings.FileSystemPicturePath, String.Format(FILE_NAME_FORMAT, download.Id.ToString(), download.Filename, download.Extension)));
				File.WriteAllBytes(filePath, data);
			}
		}

		public void Delete(Download download)
		{
			var settings = _settingService.LoadSetting<AlternativeStorageSettings>();
			if (HasValidSettings(settings))
			{
				var filePath = _webHelper.MapPath(Path.Combine(settings.FileSystemPicturePath, String.Format(FILE_NAME_FORMAT, download.Id.ToString(), download.Filename, download.Extension)));
				File.Delete(filePath);
			}
		}

		public bool HasValidSettings(AlternativeStorageSettings settings)
		{
			return !String.IsNullOrEmpty(settings.FileSystemPicturePath);
		}
	}
}